import React, { useEffect, useState } from 'react';
import './index.less';
import { IActivity, IBelong, IEntity, ITarget, IView } from '@/ts/core';
import Banner from '../WorkBench/components/Banner';
import { Space } from 'antd';
import { ViewerHost } from '@/executor/open/page/view/ViewerHost';
import ViewerManager from '@/executor/open/page/view/ViewerManager';
import { schema } from '@/ts/base';
import { DashboardTemplateHomeView } from '@/executor/open/dashboardTemplate';
import LedgerForm from '@/executor/open/view/ledger/LedgerForm';
import { TotalView } from '@/ts/core/thing/standard/view/totalView';
import { MallTemplate } from '@/executor/open/mallTemplate/pages';
import { IMallTemplate } from '@/ts/core/thing/standard/page/mallTemplate';
import { IElementHost } from '@/ts/element/standard';

interface PortalPageProps {
  target: ITarget;
  activity: IActivity;
  space: IBelong;
}
//首页网站
const PortalPage: React.FC<PortalPageProps> = ({ target, space }) => {
  const [selected, setSelected] = useState<any>();
  const [templates, setTemplates] = React.useState<schema.XCommon[]>([]);

  useEffect(() => {
    loadTemps();
  }, [target]);

  const loadTemps = async () => {
    const tabs = await target.webSiteProvider.loadTabs();
    const files = await target.webSiteProvider.searchFiles(tabs);
    setTemplates([...files]);
    setSelected(files[0]);
  };

  const renderEntity = (entity: IEntity<any>) => {
    switch (entity.typeName) {
      case '页面模板':
        return (
          <ViewerHost
            ctx={{
              view: new ViewerManager(entity as IElementHost<any>),
            }}
          />
        );
      case '视图':
        if (entity.groupTags.includes('图表视图')) {
          return <DashboardTemplateHomeView current={entity as any} />;
        } else if (entity instanceof TotalView) {
          return (
            <LedgerForm
              isFull={false}
              current={entity as IView}
              form={entity.metadata as any}
              directory={entity.directory}
            />
          );
        } else {
          return <>暂不支持</>;
        }
      case '商城模板':
        return <MallTemplate current={entity as IMallTemplate} />;
      default:
        return <>暂不支持</>;
    }
  };

  return (
    <div className="workbench-content portal-page">
      <Banner space={space} bannerkey="webSite" />
      <Space direction="horizontal" size={10}>
        {templates.map((item, idx) => (
          <a
            key={idx}
            onClick={() => setSelected(item)}
            className={`navbar-item ${
              selected.id === item.id ? 'navbar-item_selected' : ''
            }`}>
            <span className="navbar-item-text">{item.name}</span>
          </a>
        ))}
      </Space>
      <div className="portal-page-body">
        {selected?.id && renderEntity(selected.file)}
      </div>
    </div>
  );
};

export default PortalPage;
